package br.com.tenax.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import br.com.tenax.fornedor.Fornecedor;

public class FornecedorDAOimpl implements FornecedorDAO {

	public void incluir(Fornecedor fornecedor) {
		Connection conexao = null;
		try {
			conexao = DAO.getConexao();

			PreparedStatement pstm = conexao.prepareStatement("insert into "
					+ "tbfornecedor (id, nome, telefone)  values (?,?,?)");
			pstm.setInt(1, fornecedor.getId());
			pstm.setString(2, fornecedor.getNome());
			pstm.setString(3, fornecedor.getTelefone());
			pstm.executeUpdate();

			pstm.close();
			conexao.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void atualizar(Fornecedor fornecedor) {

		Connection conexao = null;
		try {
			conexao = DAO.getConexao();

			PreparedStatement pstm = conexao.prepareStatement("update "
					+ "tbfornecedor set nome = ?, telefone =?  where id =?");
			pstm.setString(1, fornecedor.getNome());
			pstm.setString(2, fornecedor.getTelefone());
			pstm.setInt(3, fornecedor.getId());
			pstm.executeUpdate();

			pstm.close();
			conexao.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void deletar(Fornecedor fornecedor) {
		Connection conexao = null;
		try {
			conexao = DAO.getConexao();

			PreparedStatement pstm = conexao.prepareStatement("delete from "
					+ "tbfornecedor where id =?");
			pstm.setInt(1, fornecedor.getId());
			pstm.executeUpdate();

			pstm.close();
			conexao.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Fornecedor consultar(Fornecedor fornecedor) {
		Fornecedor f = new Fornecedor();
		Connection conexao = null;
		try {
			conexao = DAO.getConexao();
			PreparedStatement pstm = conexao.prepareStatement("Select * from "
					+ "tbfornecedor where id =?");
			pstm.setInt(1, fornecedor.getId());
			ResultSet rs = pstm.executeQuery();
			while (rs.next()) {
				f.setId(rs.getInt("id"));
				f.setNome(rs.getString("nome"));
				f.setTelefone(rs.getString("telefone"));
			}
			pstm.close();
			conexao.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return f;
	}

	@Override
	public List<Fornecedor> listar() {
		List<Fornecedor> lista = new ArrayList<>();
		Connection conexao = null;
		try {
			conexao = DAO.getConexao();
			PreparedStatement pstm = conexao
					.prepareStatement("Select * from tbfornecedor ");

			ResultSet rs = pstm.executeQuery();
			while (rs.next()) {
				Fornecedor f = new Fornecedor();
				f.setId(rs.getInt("id"));
				f.setNome(rs.getString("nome"));
				f.setTelefone(rs.getString("telefone"));
				lista.add(f);
			}
			pstm.close();
			conexao.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lista;
	}
}